<template>
  <edit-dialog :centerDialogVisible="visible" :tilte="type.isEdit ? type.text : '查看'" :default-button="false"
    v-loading.fullscreen.lock="fullscreenLoading" @Cancel="handleCancel(2)" :width="width">
    <template #content>
      <el-dialog v-model="innerVisible" width="30%" title="驳回" append-to-body>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="审批意见：" label-width="100px" prop="comments">
              <el-input type="textarea" :rows="3" :clearable="true" v-model="ruleForm.mainForm.comments" maxlength="200"
                show-word-limit placeholder="请输入审批意见" style="width: 320px" />
            </el-form-item>
          </el-col>
        </el-row>
        <template #footer>
          <div class="dialog-footer">
            <el-button class="buttonCancel" @click="rejectCancle">取消</el-button>
            <el-button type="primary" class="btn-ok" @click="handleEditSubmit(mainForm, 6)">驳回</el-button>
          </div>
        </template>
      </el-dialog>
      <div>
        <el-form ref="mainForm" :rules="type.isEdit ? rules : {}" label-width="100px" :model="ruleForm.mainForm"
          class="demo-form-inline" label-position="top">
          <div class="content">
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item :label="'隐患名称：' + (type.isEdit ? '' : ruleForm.mainForm.tshlName)" label-width="100px"
                  prop="tshlName">
                  <el-input v-model="ruleForm.mainForm.tshlName" v-show="type.isEdit" placeholder="请输入"
                    style="width: 330px" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="'隐患分类：' + (type.isEdit ? '' : ruleForm.mainForm.tshlClassify)" label-width="100px"
                  prop="tshlClassify">
                  <el-select filterable v-show="type.isEdit" v-model="ruleForm.mainForm.tshlClassify" placeholder="请选择"
                    :clearable="true" style="width: 330px">
                    <el-option v-for="item in earlyType" :key="item.id" :label="item.earlyType" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="'隐患等级：' + (type.isEdit ? '' : ruleForm.mainForm.tshlGrade)" label-width="100px"
                  prop="tshlGrade">
                  <el-select v-model="ruleForm.mainForm.tshlGrade" v-show="type.isEdit" disabled placeholder="请选择"
                    :clearable="true" style="width: 330px">
                    <el-option v-for="item in earlyLevel" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item :label="'发现时间：' + (type.isEdit ? '' : ruleForm.mainForm.tshlUt)" label-width="100px"
                  prop="tshlUt">
                  <el-date-picker v-model="ruleForm.mainForm.tshlUt" v-if="type.isEdit" type="date" placeholder="请选择"
                    style="width: 330px" :disabled-date="discoveryOptions" value-format="YYYY-MM-DD" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="'问题来源：' + (type.isEdit ? '' : ruleForm.mainForm.sources)" label-width="100px"
                  prop="sources">
                  <el-select v-model="ruleForm.mainForm.sources" v-show="type.isEdit" placeholder="请选择"
                    style="width: 330px" filterable>
                    <el-option v-for="item in unitData" :key="item.id" :label="item.unitName" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="'责任单位：' + (type.isEdit ? '' : ruleForm.mainForm.tshlUnit)" label-width="100px"
                  prop="tshlUnit">
                  <el-select v-model="ruleForm.mainForm.tshlUnit" v-show="type.isEdit" placeholder="请选择"
                    style="width: 330px" filterable>
                    <el-option v-for="item in unitData" :key="item.id" :label="item.unitName" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item :label="'责任人：' + (type.isEdit ? '' : ruleForm.mainForm.tshlPerson)" label-width="100px"
                  prop="tshlPerson">
                  <el-input v-model="ruleForm.mainForm.tshlPerson" v-show="type.isEdit" placeholder="请输入"
                    :clearable="true" style="width: 330px" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="'责任人电话：' + (type.isEdit ? '' : ruleForm.mainForm.phone)" label-width="100px"
                  prop="phone">
                  <el-input v-model="ruleForm.mainForm.phone" v-show="type.isEdit" placeholder="请输入"
                    style="width: 330px" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="'整改时限：' + (type.isEdit ? '' : ruleForm.mainForm.tshlLimit)" label-width="100px"
                  prop="tshlLimit">
                  <el-date-picker v-model="ruleForm.mainForm.tshlLimit" v-if="type.isEdit" type="date" placeholder="请选择"
                    :clearable="true" style="width: 330px" :disabled-date="rectifyOptions" value-format="YYYY-MM-DD" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item :label="'隐患内容：' + (type.isEdit ? '' : ruleForm.mainForm.content)" label-width="100px"
                  prop="content">
                  <el-input type="textarea" v-show="type.isEdit" :rows="3" :clearable="true"
                    v-model="ruleForm.mainForm.content" maxlength="200" show-word-limit placeholder="请输入内容"
                    style="width: 1300px" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item :label="'整改要求：' + (type.isEdit ? '' : ruleForm.mainForm.request)" :clearable="true"
                  label-width="100px" prop="request">
                  <el-input type="textarea" :rows="3" v-model="ruleForm.mainForm.request" maxlength="200"
                    show-word-limit v-show="type.isEdit" placeholder="请输入整改要求" style="width: 1300px" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24" v-show="type.code === 'free'">
              <el-col :span="24">
                <el-form-item :label="'挂起原因：' + (type.isEdit ? '' : ruleForm.mainForm.pendingReason)" :clearable="true"
                  label-width="100px" prop="pendingReason">
                  <el-input type="textarea" :rows="3" v-model="ruleForm.mainForm.pendingReason" maxlength="200"
                    show-word-limit v-show="type.isEdit" placeholder="请输入挂起原因" style="width: 1300px" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24" v-show="type.code === 'back'">
              <el-col :span="24">
                <el-form-item :label="'审批意见：' + (type.isEdit ? '' : ruleForm.mainForm.comments)" :clearable="true"
                  label-width="100px" prop="comments">
                  <el-input type="textarea" :rows="3" v-model="ruleForm.mainForm.comments" maxlength="200"
                    show-word-limit v-show="type.isEdit" placeholder="请输入审批意见" style="width: 1300px" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="content">
            <el-row :gutter="24" :class="!type.isEdit ? 'hideUpload' : ''">
              <el-col :span="24">
                <el-form-item :label="type.isEdit ? '上传图片：' : '图片：'" label-width="100px" class="upload-img"
                  prop="fileListImage" :class="imglist.length >= maxImg ? 'div' : ''" ref="uploadRef">
                  <span v-if="!type.isEdit && imglist.length == 0">无</span>
                  <el-upload v-model:file-list="imglist" :disabled="!type.isEdit"
                    :action="baseGeneralPath + '/file/add'" method="post" list-type="picture-card" :limit="maxImg"
                    :on-preview="handlePre" :on-success="handlerUploadSuccess" :on-exceed="handleExceed"
                    :before-upload="handlerBeforeUpload" @change="imagelists" :on-remove="handleRemove">
                    <el-icon>
                      <Plus />
                    </el-icon>
                  </el-upload>
                  <el-dialog align-center width="auto" center v-model="dialogVisible">
                    <div>
                      <img w-full :src="dialogImageUrl" alt="图片预览" />
                    </div>
                  </el-dialog>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24" :class="type.isEdit ? '' : 'hideUpload'">
              <el-col :span="24">
                <el-form-item :label="type.isEdit ? '上传附件：' : '附件：'" label-width="100px" prop="filelist"
                  ref="fileUploadRef" :rules="[
    {
      required: true,
      trigger: 'change',
      validator: getfiles,
    },
  ]"> <span v-if="!type.isEdit && filelist.length == 0">无</span>
                  <el-upload class="upload-demo" drag method="post" :action="baseGeneralPath + '/file/add'" multiple
                    :limit="maxFile" v-model:file-list="filelist" :disabled="!type.isEdit" :on-preview="handlePre"
                    :on-success="uploadFileSuccess" :on-exceed="handleFileExceed" :before-upload="fileBeforeUpload"
                    @change="filelists" :on-remove="handleFileRemove">
                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                    <div class="el-upload__text">
                      点击或将文件拖拽到这里上传
                    </div>

                    <template #tip>
                      <div class="el-upload__tip">
                        支持扩展名：{{ fileTypStr }}
                      </div>
                    </template>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
      </div>
    </template>

    <template #custom>
      <span class="dialog-footer">
        <el-button class="buttonCancel" @click="handleCancel">取消</el-button>
        <el-button type="primary" class="btn-ok" v-if="!type.isEdit" @click="handleCancel">确定</el-button>

        <el-button type="primary" class="btn-ok" v-if="type.code === 'free' && type.isEdit"
          @click="handleEditSubmit(mainForm, 1)">解除挂起</el-button>
        <el-button type="primary" class="btn-ok" v-if="type.code === 'free' && type.isEdit"
          @click="handleEditSubmit(mainForm)">确定</el-button>

        <el-button type="primary" class="btn-ok" v-if="(type.code === 'handle' || type.code === 'back') && type.isEdit"
          @click="handleEditSubmit(mainForm)">保存</el-button>
        <el-button type="primary" class="btn-ok" v-if="(type.code === 'handle' || type.code === 'back') && type.isEdit"
          @click="handleEditSubmit(mainForm, 3)">提交</el-button>

        <el-button type="primary" class="btn-ok" v-if="type.code === 'accept' && type.isEdit"
          @click="innerVisible = true">驳回</el-button>
        <el-button type="primary" class="btn-ok" v-if="type.code === 'accept' && type.isEdit"
          @click="handleEditSubmit(mainForm, 4)">通过</el-button>
      </span>
    </template>
  </edit-dialog>
  <el-image-viewer v-if="showViewer" @close="showViewer = false" :url-list="[fileUrl]" />
  <preViewFile :visible="showFile" :fileType="fileType" :url="fileUrl" @cancel="showFile = false"></preViewFile>
</template>

<script setup lang="ts">
import editDialog from '@/components/editDialog/index.vue'
import { ref, reactive, watch, provide, onBeforeMount, defineEmits, defineProps } from 'vue'
import { useStore } from 'vuex'
import { rules } from './config/rules'
import { baseUrlConfig } from '@/config/config'
import { updateInventory, updateFiles } from '@/api/secure/inventory'
import { ElMessage, dayjs, FormInstance, UploadProps, ElMessageBox } from 'element-plus'
import {
  deleteFile,
  deleteFiles,
  downloadFiles,
  onGetFileDownloadPath,
  preViewPdf,
  preViewPPTToPdf,
  uploadFiles,
  uploadKonwledgeFiles
} from "@/api/common"
import preViewFile from '@/components/previewFile/index.vue'
const fullscreenLoading = ref(false)
const width = ref('1060px')
const emit = defineEmits(['cancel', 'submit', 'showAdd'])
const handleCancel = (data) => {
  if (data === 1 && deleteFileCodes.length > 0) {
    excuteDelFile(deleteFileCodes, () => {
      // 表单重置
      mainForm.value.resetFields()
      ruleForm.mainForm.responsibleUnit = null
      emit('cancel')
    })
  } else if (data === 2 && tempAddFileCodes.length > 0) {
    // 操作文件并取消
    excuteDelFile(tempAddFileCodes, () => {
      // 表单重置
      mainForm.value.resetFields()
      ruleForm.mainForm.responsibleUnit = null
      emit('cancel')
    })

  } else {
    // 无文件操作
    // 表单重置
    mainForm.value.resetFields()
    ruleForm.mainForm.responsibleUnit = null
    emit('cancel')
  }

}
const baseGeneralPath = baseUrlConfig.businessBaseUrl
const innerVisible = ref(false)
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  info: {
    type: Object,
    default: () => null,
  },
  data: {
    type: Object,
    default: () => null
  },
  type: {
    type: Object,
    default: null
  },
  unitData: {
    type: Array,
    default: () => null
  },
  earlyType: {
    type: Array,
    default: () => null
  },
  earlyLevel: {
    type: Array,
    default: () => null
  }
})
// 页面的数据
const ruleForm = reactive({
  loading: false,
  editId: null,
  mainForm: {
    tshlId: null,
    tshlName: null,
    tshlClassify: null,
    tshlGrade: null,
    tshlUt: null,
    sources: null,
    tshlUnit: null,
    tshlPerson: null,
    phone: null,
    tshlLimit: "",
    content: null,
    request: null,
    pictureFile: null,
    accessory: null,
    tshlStat: "1",
  }
})
const handleEditSubmit = async (formEl: any, state) => {
  // console.log('handleEditSubmit')
  // 编辑
  if (!formEl) return
  await formEl.validate((valid: any) => {
    if (valid) {
      if (state != undefined) {
        ruleForm.mainForm.tshlStat = state
        if (state === 3) {
          // 审批评论置空
          ruleForm.mainForm.comments = ''
        } else if (state === 1) {
          // 挂起原因置空
          ruleForm.mainForm.pendingReason = ''
        }
      }
      if (ruleForm.mainForm.pictureFile?.length == 0) {
        // 置空
        ruleForm.mainForm.pictureFile = null
      }
      if (ruleForm.mainForm.tshlGrade == "一般隐患") {
        ruleForm.mainForm.tshlGrade = 1
      }
      if (ruleForm.mainForm.tshlGrade == "严重隐患") {
        ruleForm.mainForm.tshlGrade = 2
      }
      if (ruleForm.mainForm.tshlGrade == "较大隐患") {
        ruleForm.mainForm.tshlGrade = 3
      }
      console.log(ruleForm.mainForm.pictureFile);
      console.log(ruleForm.mainForm.accessory);
      updateInventory(ruleForm.mainForm).then(res => {
        //将图片和附件和隐患绑定关系
        // if (res!=null) {
        if (ruleForm.mainForm.pictureFile != null) {
          for (let i = 0; i < ruleForm.mainForm.pictureFile.length; i++) {
            ruleForm.mainForm.pictureFile[i].tshlId = ruleForm.mainForm.tshlId
            updateFiles(ruleForm.mainForm.pictureFile[i]).then(res => {
              // console.log(res);
            })
          }
        }
        if (ruleForm.mainForm.accessory != null) {
          for (let i = 0; i < ruleForm.mainForm.accessory.length; i++) {
            ruleForm.mainForm.accessory[i].tshlId = ruleForm.mainForm.tshlId
            updateFiles(ruleForm.mainForm.accessory[i]).then(res => {
              // console.log(res);
            })
          }
        }
        if (state === 0) {
          rejectCancle()
        }
        handleCancel(1)
        ElMessage.success((state === 0 ? '驳回' : props.type.text) + '成功')
        // } else {
        //   ElMessage.error((state === 0 ? '驳回' : props.type.text) + '失败')
        // }
      }).catch(e => {
        ElMessage.error('服务器错误,请联系管理员')
      })

    }
  })
}
// 监听规则同步等级
watch(() => [ruleForm.mainForm.earlyId], (newValue, oldValue) => {
  props.earlyType.forEach(item => {
    if (newValue == item.id) {
      ruleForm.mainForm.tshlGrade = item.tshlGrade
    }
  })
})
// 监听责任单位
watch(() => [ruleForm.mainForm.responsibleUnit], (newValue, oldValue) => {
  console.log("newValue:" + newValue + " oldValue:" + oldValue)
  if (ruleForm.mainForm.id && oldValue[0] == null) {
    // 编辑,回显首次不联动
  } else {
    props.unitData.forEach(item => {
      if (newValue == item.id) {
        ruleForm.mainForm.person = item.principalName
        ruleForm.mainForm.phone = item.principalPhone
      }
    })
  }

})

// 表单回显
watch(() => props.data, () => {
  ruleForm.mainForm = {
    tshlId: props.data.row.tshlId,
    tshlName: props.data.row.tshlName ? props.data.row.tshlName : '',
    tshlClassify: props.data.row.tshlClassify ? props.data.row.tshlClassify : '',
    tshlGrade: props.data.row.tshlGrade ? props.data.row.tshlGrade : '',
    tshlUt: props.data.row.tshlUt ? props.data.row.tshlUt : '',
    sources: props.data.row.sources ? props.data.row.sources : '',
    tshlUnit: props.data.row.tshlUnit ? props.data.row.tshlUnit : '',
    tshlPerson: props.data.row.tshlPerson ? props.data.row.tshlPerson : '',
    phone: props.data.row.phone ? props.data.row.phone : '',
    tshlLimit: props.data.row.tshlLimit ? props.data.row.tshlLimit : '',
    content: props.data.row.content ? props.data.row.content : '',
    request: props.data.row.request ? props.data.row.request : '',
    pictureFile: props.data.row.pictureFile ? props.data.row.pictureFile : '',
    accessory: props.data.row.accessory ? props.data.row.accessory : '',
    isState: props.data.row.isState ? props.data.row.isState : '',
    comments: props.data.row.comments ? props.data.row.comments : '',
    isStateDesc: props.data.isStateDesc ? props.data.isStateDesc : '',
    problemSourcesDesc: props.data.problemSourcesDesc ? props.data.problemSourcesDesc : '',
    earlyLevelDesc: props.data.earlyLevelDesc ? props.data.earlyLevelDesc : '',
    responsibleUnitDesc: props.data.responsibleUnitDesc ? props.data.responsibleUnitDesc : '',
    earlyNameType: props.data.earlyNameType ? props.data.earlyNameType : ''
  }

  console.log(props.data);

  ruleForm.mainForm.pictureFile = props.data.pictureFile?.map((item: any) => {
    return {
      fileId: item.fileId,
      fileName: item.fileName,
      fileSize: item.fileSize,
      filePath: item.filePath,
      fileType: item.fileType,
      fileLocation: 1,
      tshlId: item.tshlId
    }
  }) || []

  ruleForm.mainForm.accessory = props.data.accessory?.map((item: any) => {
    return {
      fileId: item.fileId,
      fileName: item.fileName,
      fileSize: item.fileSize,
      filePath: item.filePath,
      fileType: item.fileType,
      fileLocation: 2,
      tshlId: item.tshlId,
      name: item.fileName
    }
  }) || []

  ruleForm.mainForm.pictureFile.forEach((item: any) => {
    item.url = item.filePath
  })

  ruleForm.mainForm.accessory.forEach((item: any) => {
    item.url = item.filePath
  })

  imglist.value = ruleForm.mainForm.pictureFile
  filelist.value = ruleForm.mainForm.accessory

  imgTempFile.value = ruleForm.mainForm.pictureFile
  tempFile.value = ruleForm.mainForm.accessory
})
const mainForm = ref<FormInstance>()
const rejectCancle = () => {
  ruleForm.mainForm.comments = ''
  innerVisible.value = false
}

// 上传图片
const imglist = ref<any[]>([])
const filelist = ref<any[]>([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
// 新增和保存成功后,需要删除的文件的code
var deleteFileCodes = []
// 取消需要删除的文件code
var tempAddFileCodes = []
// 文件数量限制
const maxFile = ref(5)
const maxImg = ref(5)
const getfiles = (rule: any, value: any, callback: any) => {
  if (!filelist.value.length) {
    callback('请上传附件')
  }
  callback()
}
const handlePictureCardPreview = (uploadFile: any) => {
  // console.log(uploadFile.url)
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

/**
 * 预览
 */
const fileUrl = ref()
const fileType = ref()
const showFile = ref(false)
const showViewer = ref(false)
const handlePre = async (data: any) => {
  fullscreenLoading.value = true
  if (data.response) {
    data = data.response.data
  }
  try {
    if (data.enclosureSuffix != 'pdf' && !/(.jpg|.jpeg|.png|.gif|.bmp|.svg)/.test(data.url)
      && (data.enclosureSuffix != 'xls' && data.enclosureSuffix != 'xlsx')) {
      // 非图片和表格和pdf转 为pdf
      preViewPdf(data.enclosureCode).then(res => {
        fullscreenLoading.value = false
        // console.log(res)
        const blob = new Blob([res], { type: "application/pdf" })
        fileUrl.value = URL.createObjectURL(blob)
        fileType.value = 'pdf'
        showFile.value = true
      }).catch(e => {
        fullscreenLoading.value = false
        ElMessageBox.confirm(
          '当前文件不支持预览,是否下载?',
          '确认',
          {
            cancelButtonText: '取消',
            confirmButtonText: '下载',
            type: 'warning'
          }
        ).then(() => {
          downloadFile(data)
        }).catch(() => {
        })
      })
    } else if (data.enclosureSuffix == 'xls' || data.enclosureSuffix == 'xlsx') {
      fullscreenLoading.value = false
      ElMessageBox.confirm(
        '当前文件不支持预览,是否下载?',
        '确认',
        {
          cancelButtonText: '取消',
          confirmButtonText: '下载',
          type: 'warning'
        }
      ).then(() => {
        downloadFile(data)
      }).catch(() => {
      })
    } else {
      onGetFileDownloadPath(data.enclosureCode).then(res => {
        fullscreenLoading.value = false
        // console.log(res)
        if (data.enclosureSuffix == 'pdf') {
          const blob = new Blob([res], { type: "application/pdf" })
          fileUrl.value = URL.createObjectURL(blob)
          fileType.value = 'pdf'
          showFile.value = true
        } else {
          const blob = new Blob([res], { type: "application/png" })
          fileUrl.value = URL.createObjectURL(blob)
          showViewer.value = true
        }
      }).catch(e => {
        fullscreenLoading.value = false
        ElMessageBox.confirm(
          '当前文件不支持预览,是否下载?',
          '确认',
          {
            cancelButtonText: '取消',
            confirmButtonText: '下载',
            type: 'warning'
          }
        ).then(() => {
          downloadFile(data)
        }).catch(() => {
        })
      })
    }
  } catch (e) {
    fullscreenLoading.value = false
    ElMessageBox.confirm(
      '当前文件不支持预览,是否下载?',
      '确认',
      {
        cancelButtonText: '取消',
        confirmButtonText: '下载',
        type: 'warning'
      }
    ).then(() => {
      downloadFile(data)
    }).catch(() => {
    })
  }
}
const downloadFile = async (uploadFile: any) => {
  var enclosureCode = ''
  var fileName = ''
  enclosureCode = uploadFile.enclosureCode
  fileName = uploadFile.enclosureName + '.' + uploadFile.enclosureSuffix
  if (!enclosureCode) {
    ElMessage.error(`文件地址不存在`)
    return
  }
  try {
    const res = await downloadFiles(enclosureCode)
    const blob = new Blob([res], { type: 'application/octet-stream' })
    const a = document.createElement("a")
    const objectUrl = URL.createObjectURL(blob)
    a.href = objectUrl
    a.download = fileName
    a.click()
    URL.revokeObjectURL(a.href)
  } catch (e) {
    ElMessage.error(`下载失败`)
  }
}
//上传成功
interface FileFace {
  enclosureContent: string
  enclosureName: string
  enclosureSuffix: string
  resourceAddress: string
  enclosureCode: string
}
const imgTempFile = ref<Array<any>>([])
const tempFile = ref<Array<any>>([])
const hideImgUpload = ref(false)
const hideFileUpload = ref(false)
// 图片上传成功
const handlerUploadSuccess: UploadProps['onSuccess'] = (resp, uploadFile, uploadFiles) => {
  // console.log(resp, uploadFile, uploadFiles)
  if (resp) {
    const item: FileFace = {
      fileId: resp.fileId,
      fileName: resp.fileName,
      fileSize: resp.fileSize,
      filePath: resp.filePath,
      fileType: resp.fileType,
      fileLocation: 1,
      tshlId: null
    }
    // tempAddFileCodes.push(item.enclosureCode)
    imgTempFile.value.push(item)
    // console.log(imgTempFile.value)
    ruleForm.mainForm.pictureFile = imgTempFile.value
    if (imgTempFile.value.length >= maxImg.value) {
      hideImgUpload.value = true
    }
  }
}
// 文件上传成功
const uploadFileSuccess: UploadProps['onSuccess'] = (resp, uploadFile, uploadFiles) => {
  // console.log(resp, uploadFile, uploadFiles)
  if (resp) {
    const item: FileFace = {
      fileId: resp.fileId,
      fileName: resp.fileName,
      fileSize: resp.fileSize,
      filePath: resp.filePath,
      fileType: resp.fileType,
      fileLocation: 2,
      tshlId: null
    }
    // tempAddFileCodes.push(item.enclosureCode)
    tempFile.value.push(item)
    console.log(tempFile.value);
    // alert(111)

    // console.log(fileTempFile.value)
    ruleForm.mainForm.accessory = tempFile.value
    console.log(ruleForm.mainForm.accessory);

    if (tempFile.value.length >= maxFile.value) {
      hideFileUpload.value = true
    }

  }
}
// 超出警告框
const handleExceed: UploadProps['onExceed'] = () => {
  ElMessage.error('上传图片数不能超过' + maxImg.value + '个')

}
const handleFileExceed: UploadProps['onExceed'] = () => {
  ElMessage.error('上传文件数不能超过' + maxFile.value + '个')
}

// 图上传前
const handlerBeforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // console.log(rawFile)
  const fileSuffix = rawFile.name.substring(rawFile.name.lastIndexOf('.') + 1)

  const whiteList = ['jpg', 'png', 'JPG', 'PNG']
  if (whiteList.indexOf(fileSuffix) === -1) {
    ElMessage.error('上传图片类型只能是 jpg,png格式')
    return false
  }

  if (rawFile.size > 10 * 1024 * 1024) {
    ElMessage.error('文件大小只能在10M以内')
    return false
  }

}
const fileTypStr = ref('rar,zip,doc,docx,pdf,xlsx,xls,ppt,pptx,txt,mp4,wms,png,jpg')
// 文件上传前
const fileBeforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // console.log(rawFile)
  const fileSuffix = rawFile.name.substring(rawFile.name.lastIndexOf('.') + 1)
  const whiteList = fileTypStr.value.split(',').concat(fileTypStr.value.toUpperCase().split(','))
  if (whiteList.indexOf(fileSuffix) === -1) {
    ElMessage.error('上传文件类型只能是' + fileTypStr.value + '格式')
    return false
  }

  if (rawFile.size > 10 * 1024 * 1024) {
    ElMessage.error('文件大小只能在10M以内')
    return false
  }

}
const uploadRef = ref()
const fileUploadRef = ref()
const filelists = async () => {
  if (!filelist.value.length) {
    fileUploadRef.value.clearValidate()
  }

}
const imagelists = async () => {
  if (!imglist.value.length) {
    uploadRef.value.clearValidate()
  }

}
const delFile = (code: string) => {
  deleteFileCodes.push(code)
}
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
  let code = ''
  if (uploadFile.fileName) {
    code = uploadFile.fileId
  } else {
    code = uploadFile.fileId
  }
  ruleForm.mainForm.pictureFile = ruleForm.mainForm.pictureFile.filter(item => item.FileId != code)
  delFile(code)
  hideImgUpload.value = false
  imgTempFile.value = imgTempFile.value.filter(item => item.enclosureCode != code)
}
const handleFileRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  // console.log(uploadFile, uploadFiles)
  let code = ''
  if (!uploadFile.url) {
    code = uploadFile.fileId;
  } else {
    code = uploadFile.fileId
  }
  ruleForm.mainForm.accessory = ruleForm.mainForm.accessory.filter(item => item.fileId != code)
  delFile(code)
  hideFileUpload.value = false
  tempFile.value = tempFile.value.filter(item => item.fileId != code)
}
const discoveryOptions = (time) => {
  return time.getTime() > Date.now()
}

const rectifyOptions = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}
const useImgurl = (url: string) => {
  const imgUrls = '/general-business'
  if (url.includes('/filePath')) {
    url = url.replace('/filePath', '')
  }
  if (url.includes('/api')) {
    url = url.replace('/api', '')
  }
  if (url.includes('/general-business')) {
    url = url.replace('/general-business', '')
  }
  return imgUrls + url
}
const excuteDelFile = (codes, callback) => {
  console.log(codes);
  if (codes != null) {
    for (let i = 0; i < codes.length; i++) {
      let data = {
        fileId: codes[i]
      }
      deleteFiles(data).then(res => {
        if (res) {
          deleteFileCodes = []
          tempAddFileCodes = []
          callback()
        }
      }).catch(e => {
        ElMessage.error('文件保存异常')
      })
    }
  }
}
</script>

<style scoped lang="less">
/* 查看隐藏文件上传 */
.hideUpload {

  /deep/ .el-upload,
  .el-upload--picture-card {
    display: none;
  }

  /deep/ .el-upload__tip {
    display: none;
  }

  /deep/ .upload-demo {
    min-width: 300px;
  }
}
</style>
